<template>
    <div class="table-container">
        <a-skeleton active :loading="loading">
            <template #default>
                <a-table :columns="postsColumns" :data-source="userPostsList" :pagination="pagination" bordered
                    @change="handleTableChange">
                    <template #bodyCell="{ column, record }">
                        <template v-if="column.key === 'title'">
                            <router-link :to="getLinkPath(record)" class="post-title-link">
                                {{ record.title }}
                            </router-link>
                        </template>

                        <template v-if="column.key === 'content'">
                            <router-link :to="getLinkPath(record)" class="post-content-link">
                                <div class="post-content" v-html="truncateContent(sanitizeHtml(record.content), 50)">
                                </div>
                            </router-link>
                        </template>

                        <template v-if="column.key === 'tags'">
                            <div class="tags-container">
                                <a-tag v-for="tag in record.tags" :key="tag" color="blue">
                                    {{ tag }}
                                </a-tag>
                            </div>
                        </template>

                        <template v-if="column.key === 'status'">
                            <a-tag :color="record.releaseFlag === 'Y' ? 'success' : 'warning'">
                                {{ record.releaseFlag === 'Y' ? '已发布' : '草稿' }}
                            </a-tag>
                        </template>

                        <template v-if="column.key === 'editTime'">
                            {{ formatDate(record.editTime) }}
                        </template>

                        <template v-if="column.key === 'action'">
                            <a-space>
                                <template v-if="record.releaseFlag !== 'Y'">
                                    <a-button type="link" @click="goToEdit(record)">
                                        继续编辑
                                    </a-button>
                                </template>
                                <template v-if="record.releaseFlag === 'Y'">
                                    <a-button type="link" @click="goToEdit(record)">
                                        编辑
                                    </a-button>
                                </template>
                                <a-button type="link" danger @click="handleDelete(record)">删除</a-button>
                            </a-space>
                        </template>
                    </template>
                </a-table>
            </template>
        </a-skeleton>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import DOMPurify from 'dompurify';
import { deletePosts, getUserPostsList } from '@/api/front/social';
import { PostsVO } from '@/api/front/social/types';

const router = useRouter();
const loading = ref(false);
const userPostsList = ref<PostsVO[]>([]);

const postsColumns = [
    {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
        width: '15%',
    },
    {
        title: '内容',
        dataIndex: 'content',
        key: 'content',
        width: '35%',
    },
    {
        title: '标签',
        dataIndex: 'tags',
        key: 'tags',
        width: '15%',
    },
    {
        title: '发表时间',
        dataIndex: 'editTime',
        key: 'editTime',
        width: '15%',
        sorter: true,
    },
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: '5%',
    },
    {
        title: '操作',
        key: 'action',
        width: '15%',
    }
];

const pagination = {
    total: 0,
    current: 1,
    pageSize: 10,
    showSizeChanger: false,
    showTotal: (total: number) => `共 ${total} 条`
};

const getList = async () => {
    loading.value = true;
    try {
        const res = await getUserPostsList({
            pageNum: pagination.current,
            pageSize: pagination.pageSize,
            orderByColumn: 'edit_time',
            isAsc: 'desc',
            categoryId: 0
        });
        userPostsList.value = res.data.rows;
        pagination.total = res.data.total;
    } catch (error) {
        message.error('获取数据失败');
    } finally {
        loading.value = false;
    }
};

const handleTableChange = (pag: any) => {
    pagination.current = pag.current;
    getList();
};

const truncateContent = (content: string, maxLength: number) => {
    const tempElement = document.createElement('div');
    tempElement.innerHTML = content;
    const text = tempElement.innerText || tempElement.textContent;
    return text.length > maxLength ? text.slice(0, maxLength) + '...' : text;
};

const sanitizeHtml = (content: string) => {
    return DOMPurify.sanitize(content);
};

const formatDate = (dateStr: string) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

const getLinkPath = (record: any) => {
    return record.releaseFlag === 'Y'
        ? { path: '/social/detail', query: { postId: record.postId } }
        : { path: '/user/postEdit', query: { postId: record.postId } };
};

const goToEdit = (record: any) => {
    router.push({
        path: '/user/postEdit',
        query: { postId: record.postId }
    });
};

const handleDelete = async (record: any) => {
    try {
        await deletePosts({ ids: [record.postId] });
        message.success('删除成功');
        await getList();
    } catch (error) {
        message.error('删除失败');
    }
};

defineExpose({
    getList
});
</script>

<style lang="scss" scoped>
.post-title-link {
    font-weight: 500;
    color: #262626;
    text-decoration: none;

    &:hover {
        color: #1890ff;
    }
}

.post-content-link {
    text-decoration: none;

    &:hover {
        .post-content {
            color: #1890ff;
        }
    }

    .post-content {
        color: #595959;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        transition: color 0.3s;
    }
}

:deep(.ant-table-thead > tr > th) {
    background: #fafafa;
    font-weight: 500;
}

:deep(.ant-table-tbody > tr > td) {
    vertical-align: top;
}

.tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;

    :deep(.ant-tag) {
        margin: 0;
        cursor: default;

        &:hover {
            opacity: 0.85;
        }
    }
}
</style> 